package com.hpx.javaeye.component;

import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.component.ListField;
import net.rim.device.api.ui.component.ListFieldCallback;

public class ComplexList extends ListField {

	private RowManager[] _rows;
 
	public ComplexList(Field[][] contents) {
		int numRows = contents.length;

		// Create a row manager for each row.
		_rows = new RowManager[numRows];
		for (int curRow = 0; curRow < numRows; curRow++) {
			_rows[curRow] = new RowManager(contents[curRow]);
		}

		// Configure this ListField to operate with TableListField semantics.
		setSize(numRows);
		setCallback(RENDERER);
	}

	private int getColumnStart(int col) {
		int columnStart = 0;
		for (int i = 0; i < col; i++) {
			columnStart += getPreferredWidth() / 3;
		}
		return columnStart;
	}

	private class RowManager extends Manager {

		public RowManager(Field[] fields) {
			super(0);
			for (int i = 0; i < fields.length; i++) {
				add(fields[i]);
			}
			setRowHeight(120);
		}

		protected void sublayout(int width, int height) {
			for (int i = 0; i < getFieldCount(); i++) {
				Field f = getField(i);
				layoutChild(f, width / 2, height);
				setPositionChild(f, getColumnStart(i), 0);
			}
			setExtent(getPreferredWidth(), getPreferredHeight());
		}

		public void drawRow(Graphics g, int x, int y, int width, int height) {
			// Arrange the cell fields within this row manager.
			layout(width, height);

			// Place this row manager within its enclosing list.
			setPosition(x, y);

			// Apply a translating/clipping transformation to the graphics
			// context so that this row paints in the right area.
			g.pushRegion(getExtent());

			// Paint this manager's controlled fields.
			subpaint(g);

			// Restore the graphics context.
			g.popContext();
		}

		public int getPreferredWidth() {
			return RENDERER.getPreferredWidth(ComplexList.this);
		}

		public int getPreferredHeight() {
			return getRowHeight();
		}
	}

	private static final ListFieldCallback RENDERER = new ListFieldCallback() {

		public void drawListRow(ListField listField, Graphics graphics,
				int index, int y, int width) {
			ComplexList cl = (ComplexList) listField;
			RowManager rowManager = cl._rows[index];
			rowManager.drawRow(graphics, 0, y, width, cl.getRowHeight());
		}

		public Object get(ListField listField, int index) {
			ComplexList cl = (ComplexList) listField;
			return cl._rows[index];
		}

		public int getPreferredWidth(ListField listField) {
			return Graphics.getScreenWidth();
		}

		public int indexOfList(ListField listField, String prefix, int start) {
			return -1;
		}

	};

}